/*
 * $Id: PictureViewer.java 182 2009-06-04 16:30:30Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.apps.pictureviewer.widget;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JComponent;

import deltadesk.apps.pictureviewer.util.GraphicsUtil;

/**
 * PictureViewer
 * 
 * @author Andreas Meyer
 * @version $Revision: 182 $
 */
public class PictureViewer extends JComponent {

	/** The serial version UID. */
	private static final long serialVersionUID = 2623806357013310697L;
	
	/** The AWT image. */
	private BufferedImage image;


	/**
	 * Construct the viewer.
	 * 
	 */
	public PictureViewer() {
		
		setBackground(Color.BLACK);
	}

	/**
	 * Set the image source and load the image.
	 * 
	 * @param file
	 * @throws IOException
	 */
	public void setSource(final File file) throws IOException {
		
		System.out.flush(); // Fix for reading TIFF files
		image = ImageIO.read(file);
		if(image == null) {
			throw new IOException("Failed reading image " + file.getName());
		}
		repaint();
	}

	/**
	 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
	 */
	@Override
	protected void paintComponent(final Graphics g) {
		
		if(image == null) {
			return;
		}

		Graphics2D g2 = (Graphics2D)g;
		
		g2.setColor(getBackground());
		g2.fillRect(0, 0, getWidth(), getHeight());
		
		final Rectangle rect = GraphicsUtil.fitRectangleInto(
				getWidth(),
				getHeight(), 
				image.getWidth(),
				image.getHeight(),
				false);
			
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2.drawImage(image, rect.x, rect.y, rect.width, rect.height, null);
	}

}
